<template>
  <van-panel>
    <van-grid :gutter="10" :column-num="3">
      <van-grid-item :text="i" v-for="(i, index) in hcarr" :key="index" />
    </van-grid>

    <van-grid :gutter="10" :column-num="3">
      <van-grid-item text="上海" />
      <van-grid-item text="北京" />
      <van-grid-item text="广州" />
      <van-grid-item text="深圳" />
      <van-grid-item text="武汉" />
      <van-grid-item text="天津" />
      <van-grid-item text="西安" />
      <van-grid-item text="南京" />
      <van-grid-item text="杭州" />
      <van-grid-item text="成都" />
      <van-grid-item text="重庆" />
    </van-grid>
    <van-index-bar :index-list="indexList">
      <template v-for="(item, index) in citylist">
        <van-index-anchor :index="item.initial" :key="index.initial" />
        <van-cell
          v-for="(i, ind) in item.list"
          :title="i.name"
          :key="index + '-' + ind"
          @click="addChange(i.code, i.name)"
        />
      </template>
    </van-index-bar>
  </van-panel>
</template>

<script>
export default {
  name: "CityList",
  data() {
    return {
      citylist: [],
      indexList: [
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "J",
        "K",
        "L",
        "M",
        "N",
        "P",
        "Q",
        "R",
        "S",
        "T",
        "W",
        "X",
        "Y",
        "Z",
      ],
      addArr: [],
      hcarr: [],
    };
  },
  mounted() {
    console.log(666);
    this.hcarr =
      sessionStorage.getItem("address") == null
        ? []
        : JSON.parse(sessionStorage.getItem("address"));

    this.$axios.get("./json/city.json").then((res) => {
      this.citylist = res.data.city;
    });
  },
  methods: {
    addChange(code, name) {
      //changeCity
      this.$store.commit("changeCity", { id: code, name: name });
      this.$router.push("/");

      //判断之前有没有本地存储，有就get，没有就是空数组
      const result =
        sessionStorage.getItem("address") == null
          ? []
          : JSON.parse(sessionStorage.getItem("address"));
      console.log(result);
      var res = name;
      result.unshift(res);
      //去重，但是返回的是对象----new Set
      let newarr=new Set(result)
      console.log(this.addArr);
      //获取key为address的json对象的值，Array.form转数组
      sessionStorage.setItem("address", JSON.stringify(Array.from(newarr)));
    },
  },
};
</script>

<style>
</style>